package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams dto) {
        SearchRequest request = new SearchRequest("hotel");
//        String key = dto.getKey();
//        if (key == null || key.isEmpty()) {
//            request.source().query(QueryBuilders.matchAllQuery());
//        } else {
//            request.source().query(QueryBuilders.matchQuery("all", dto.getKey()));
//        }
        buildBasicQuery(dto, request);
        // 2.2.分页
        int page = dto.getPage();
        int size = dto.getSize();
        request.source().from((page - 1) * size).size(size);

        //2.3 距离排序
        String location = dto.getLocation();
        if (location != null && !location.isEmpty()) {
            request.source().sort(SortBuilders
                    .geoDistanceSort("location", new GeoPoint(location))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS));
        }


        try {
            //解析响应
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            SearchHits searchHits = response.getHits();
            // 3.获取总数
            long totalSize = searchHits.getTotalHits().value;
            // 4.获取hit数据数组
            SearchHit[] hits = searchHits.getHits();
            // 5.获取数据
            List<HotelDoc> hotelDocs = new ArrayList<>();
            if (hits != null && hits.length > 0) {
                for (SearchHit hit : hits) {
                    // 获取json数据
                    String hitJson = hit.getSourceAsString();
                    // 反序列化
                    HotelDoc hotelDoc = JSON.parseObject(hitJson, HotelDoc.class);
                    // 获取排序值
                    Object[] sortValues = hit.getSortValues();
                    if (sortValues != null && sortValues.length > 0) {
                        Object sortValue = sortValues[0];
                        hotelDoc.setDistance(sortValue);
                    }
                    hotelDocs.add(hotelDoc);
                }
            }
            return new PageResult(totalSize, hotelDocs);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 过滤条件
    private void buildBasicQuery(RequestParams dto, SearchRequest request) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        String key = dto.getKey();
        if (key == null || key.isEmpty()) {
            request.source().query(QueryBuilders.matchAllQuery());
        } else {
            request.source().query(QueryBuilders.matchQuery("all", dto.getKey()));
        }
        // 城市条件
        String city = dto.getCity();
        if (city != null && !city.isEmpty()) {
            boolQueryBuilder.must(QueryBuilders.termQuery("city", city));
        }
        // 品牌条件
        String brand = dto.getBrand();
        if (brand != null && !brand.isEmpty()) {
            boolQueryBuilder.must(QueryBuilders.termQuery("brand", brand));
        }
        // 价格区间条件
        if (dto.getMinPrice() != null && dto.getMaxPrice() != null) {
            boolQueryBuilder.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(dto.getMinPrice())
                    .lte(dto.getMaxPrice()));
        }
        // 星级条件
        String starName = dto.getStarName();
        if (starName != null && !starName.isEmpty()) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("starName", starName));
        }

        // 2.算分控制 竞价排名
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQueryBuilder,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(10)
                                )
                        });

        request.source().query(functionScoreQuery);
    }
}

